// ==UserScript==
// @name         伙伴云助手
// @namespace    http://tampermonkey.net/
// @version      2021.5.26
// @description  方便跳转到生意参谋看竞对产品数据，不用切换页面看不同飞猪产品的数据
// @author       ╮(╯▽╰)╭
// @updateURL    https://gitee.com/amutravel/others/raw/master/huobanyun/hbyHelper/hbyHelper.user.js
// @downloadURL  https://gitee.com/amutravel/others/raw/master/huobanyun/hbyHelper/hbyHelper.user.js
// @run-at       document-end
// @match        https://sycm.taobao.com/mc/ci/item/monitor?*
// @match        https://app.huoban.com/tables/2100000015127529*
// @match        http://fp.lxfx.xyz:9010/*
// @connect      wangmaijia.cn
// @connect      fp.lxfx.xyz
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addValueChangeListener
// @grant        GM_notification
// @grant        unsafeWindow
// @require      https://cdn.bootcdn.net/ajax/libs/vue/3.0.2/vue.global.prod.js

// match        http://127.0.0.1:9010/*
// require      file:///D:/nut/codes/jsLib/vue3.global.js
// require      file:///D:/nut/codes/js/huobanyun/hbyHelper/hbyHelper.user.js
// ==/UserScript==
(function() {

unsafeWindow.Vue = Vue;
const SERVER = "http://fp.lxfx.xyz:9010";
if (location.hostname === "sycm.taobao.com") {
  GM_addStyle(`
    #sycmVueApp{
      position: fixed;
      left: 10px;
      top: 110px;
      max-width: 110px;
      z-index: 99999999;
      background: white;
      border-radius: 5px;
      box-shadow: 2px 2px 3px 2px #2DA89D;
      font-size: 14px;
      font-family: "微软雅黑";
    }
    .fgLi{
      list-style-type: none;
      padding: 2px;
      border-left: 3px solid white;
      display: flex;
      justify-content: center;
    }
    .fgLi>span:first-child{
      cursor: pointer;
      width: calc(100% - 25px)
    }
    .currentLi,
    .fgLi:hover{
      border-left: 3px solid #2DA89D;
      background-color: #2DA89D20;
    }
    #sycmVueApp button{
      cursor: pointer;
      background-color: #f3d024;
      color: #0040c1;
      padding: 2px 3px;
      border-radius: 3px;
    }
  `);
  // 生意参谋页面的UI
  const createSycmUI = () => {
    let ele = document.createElement('DIV');
    ele.id = "sycmVueApp";
    document.body.appendChild(ele);
    ele.innerHTML = `
      <div id="projectName">
        <button v-for="item in fgProjects.name"
          v-text="item.name"
          @click="getProjectSupsByProjectName(item.name)"
        ></button>
      </div>
      <div id="sups">
        <li 
          v-for="sup in fgProjects.sups" 
          :class="['fgLi', fgProjects.currentId==sup.id?'currentLi':'']"
          :title="sup.id">
          <span @click="getWmjDataById(sup.id)" v-text="sup.name"></span>
          <button @click="openSalePage(sup.id)">🔗</button>
        </li>
      </div>
    `;
  };
  let fgProjects = Vue.reactive({ name: [], sups: [], currentId: '' });
  // 根据竞对项目名称，获取项目详情，进而获得商家ID
  const getProjectSupsByProjectName = (name) => {
    GM_xmlhttpRequest({
      url: SERVER+'/project/fgHelper',
      method: 'POST',
      data: JSON.stringify({ oper: 'getSups', name: name, platform: 'fg' }),
      responseType: 'json',
      onload: (resp) => {
        if (Array.isArray(resp.response) && resp.response.length) {
          let detail = JSON.parse(resp.response[0].code);
          let sups = detail.spus;
          Object.assign(fgProjects, { sups })
        }
      },
      onerror: (resp) => {
        console("getProjectSupsByProjectName Error:", resp)
      },
    })
  };

  // 根据产品ID获取旺卖价数据，其实就是填充 Input 元素和 点击[获取数据]按钮而已
  const getWmjDataById = (id) => {
    Object.assign(fgProjects, { currentId: id })
    document.querySelector("input.layui-input[name=info]").value = id
    document.querySelector("button.layui-btn[func=change]").click()
  };

  // 跳转到前端售卖页面
  const openSalePage = (id)=>{window.open(`https://traveldetail.fliggy.com/item.htm?id=${id}`, "_blank")}

  createSycmUI();
  unsafeWindow.sycmHelper = Vue.createApp({
    setup() {
      Vue.onMounted(() => {
        GM_addValueChangeListener('SYCM_PROJECT_NAME', (name, old_value, new_value, remote) => {
          if (new_value.length) {
            Object.assign(fgProjects, { name: new_value })
            getProjectSupsByProjectName(fgProjects.name[0].name)
            GM_notification({ highlight: true })
          }
        })
      })

      return { fgProjects, getProjectSupsByProjectName, getWmjDataById, openSalePage }
    }
  }).mount("#sycmVueApp")
} else if (location.href.includes("https://app.huoban.com/tables/2100000015127529")) {
  GM_addStyle(`
    #sycmVueApp{
      position: fixed;
      left: 60px;
      top: 5px;
      max-width: 175px;
      z-index: 99999999;
      background: white;
      border-radius: 5px;
      box-shadow: 2px 2px 3px 2px #008ED2;
      font-size: 14px;
      font-family: "微软雅黑";
    }
    #sycmVueApp:hover{ max-width: 300px; }
    .warning{ color:white; background: #F5BD00 !important; }
    .error{ color:white; background: #EB3941 !important; }
    .success{ color:white; background: #0AEA6A !important;}
    .fgLi{
      list-style-type: none;
      padding: 2px;
      border-left: 3px solid white;
      display: flex;
      justify-content: center;
      white-space: nowrap;
      line-height: 22px;
    }
    #sycmVueApp .fgLi>span:nth-child(2){display:none;}
    .fgLi>span:first-child{
      cursor: pointer;
      width: 100%
    }
    #sycmVueApp:hover .fgLi>span:nth-child(2){display: inline;}
    #sycmVueApp:hover .fgLi>span:first-child{
      width: calc(100% - 140px)
    }
    .currentLi,
    .fgLi:hover{
      border-left: 3px solid #005fe5;
      background-color: rgba(0,95,229,.1);
    }
    #sycmVueApp button{
      cursor: pointer;
      background-color: #008ED2;
      border:0;
      color: white;
      padding: 3px 10px;
      margin: 5px;
      border-radius: 3px;
    }
    #sycmVueApp .fgLi button{ 
      margin:0 0 0 3px;
      padding-top: 1px !important;
      padding-bottom:1px !important;
    }
  `);
  // 伙伴云页面UI
  const createHbyUI = () => { 
    let ele = document.createElement('DIV');
    ele.id = "sycmVueApp";
    document.body.appendChild(ele);
    ele.innerHTML = `
      <div>
        <button @click="getPageData">抓取</button>
        <button @click="vState.rows = []">清空</button>
        <br>
        <button v-if="vState.msg.content.length" :class="vState.msg.type" v-text="vState.msg.content"></button>
      </div>
      <div>
        <button onclick="window.open('https://sycm.taobao.com/mc/ci/item/monitor', '_blank')">生</button>
        <button onclick="window.open('http://fp.lxfx.xyz:9010/mt', '_blank')">美</button>
        <button onclick="window.open('http://fp.lxfx.xyz:9010/mfw', '_blank')">马</button>
        <button onclick="window.open('http://fp.lxfx.xyz:9010/fg', '_blank')">猪</button>
      </div>
      <div>
        <li v-for="row in vState.rows" :class="['fgLi', vState.currentId==row.poiId?'currentLi':'']">
          <span v-text="row.name"></span>
          <span>
            <button @click="jump2Sycm(row.poiId)">生</button>
            <button @click="jump2PlatformPorject(row.poiId, 'mt')">美</button>
            <button @click="jump2PlatformPorject(row.poiId, 'mfw')">马</button>
            <button @click="jump2PlatformPorject(row.poiId, 'fg')">猪</button>
          </span>
        </li>
      </div>
    `;
  };

  let vState = Vue.reactive({
    currentId: '',
    rows: [],
    abstract: '', // 内容摘要，如果摘要有变化，就更新
    msg: {type:'', content: ''}
  });

  const getPageData = ()=>{
    // 伙伴云行元素
    let rows = $(".fixedDataTableLayout_rowsContainer>div:nth-child(3)>div");
    let rowsData = [];
    if(rows.length >=3){
      rows.each((index, elem)=>{
        let tds = $(elem).find('.cellContent_main');
        tds.length && rowsData.push({index:$(elem).find('.index_num').text(), name: tds[0].textContent, poiId: tds[1].textContent})
      })
      rowsData.sort((a,b)=>{return parseInt(a.index) - parseInt(b.index)});
      Object.assign(vState, {rows: rowsData, msg:{type:'', content: ''}})
    }else{
      Object.assign(vState, {rows: [], msg:{type:'warning', content: '没有行记录'}})
    }
  };
  // 检查行内容是否有变动，如果有变动，就更新抓取
  const checkChange = ()=>{
    try {
      if(!vState.rows.length) return;
      if(!location.href.includes("tables/2100000015127529")) return;
      let tableText = $(".fixedDataTableLayout_rowsContainer>div:nth-child(3)>div").text();
      let abstract = tableText.slice(0,30) + tableText.slice(-30);
      if( vState.abstract != abstract) { 
        getPageData()
        Object.assign(vState, {abstract: abstract});
        console.info('[excute checkChange error]:', error)
      }
    } catch (error) { console.info('[checkChange excuted]') }
  };
  const getPlatformProjectName = (poiId, platform)=>{
    Object.assign(vState, {currentId: poiId})
    return new Promise(resolve=>{
      GM_xmlhttpRequest({
        url: SERVER+'/project/fgHelper',
        method: 'POST',
        responseType: 'json',
        data: JSON.stringify({
          oper: 'getProjectName',
          poiId: poiId.padStart(8, '0'),
          platform: platform
        }),
        onload: (resp)=>{ resolve(resp) },
        onerror: (resp)=>{ resolve(resp) }
      })
    })
  };
  // 跳去生意参谋，如果有项目的话
  const jump2Sycm = (poiId)=>{
    Object.assign(vState, {currentId: poiId, msg: {type:'', content: ''}});
    getPlatformProjectName(poiId, 'fg').then(resp=>{
      if(resp.status==200){
        if(resp.response.length){
          GM_setValue('SYCM_PROJECT_NAME', [])
          GM_setValue('SYCM_PROJECT_NAME', resp.response)
          Object.assign(vState, {msg: {type:'success', content:resp.response.length+'个竞对项目'}})
        }else{
          Object.assign(vState, {msg: {type:'warning', content:'没有飞猪竞对项目'}})
        }
      }else{
        Object.assign(vState, {msg: {type:'error', content:'网络出错或请求出错,请重试或联系维护人'}})
      }
    }).catch(error=>{
      Object.assign(vState, {msg: {type:'error', content:'网络出错,请重试:'+error.response}})
    })
  };
  // 跳去平台竞对项目
  const jump2PlatformPorject = (poiId, platform)=>{
    getPlatformProjectName(poiId, platform)
      .then(resp=>{
        if(resp.status==200){
          if(resp.response.length){
            GM_setValue('PLATFORM_PROJECT_NAME', [])
            GM_setValue('PLATFORM_PROJECT_NAME', resp.response)
            Object.assign(vState, {msg: {type:'success', content:resp.response.length+'个竞对项目'}})
          }else{
            Object.assign(vState, {msg: {type:'warning', content:'没有竞对项目'}})
          }
        }else{
          Object.assign(vState, {msg: {type:'error', content:'网络出错或请求出错,请重试或联系维护人'}})
        }
      })
      .catch(error=>{})
  }

  createHbyUI()
  unsafeWindow.sycmHelper = Vue.createApp({
    setup() {
      setInterval(() => {
        checkChange();
      }, 2500);
      return { vState, getPageData, jump2Sycm, jump2PlatformPorject }
    }
  }).mount("#sycmVueApp")

} else if(location.origin === "http://fp.lxfx.xyz:9010"){
  GM_addValueChangeListener('PLATFORM_PROJECT_NAME', (name, old_value, new_value, remote) => {
    const setSearch = {
      mt: (name)=>{unsafeWindow.emitter.emit("setSearch", name)},
      mfw: (name)=>{unsafeWindow.emitter.emit("setSearch", name)},
      fg: (name)=>{unsafeWindow.emitter.emit("setSearch", name)}
    }
    if (new_value.length && location.pathname.slice(1) === new_value[0].platform) {
      setSearch[new_value[0].platform](new_value[0].name)
      GM_notification({ highlight: true })
    }
  })
}

})();